const db = wx.cloud.database({
  env: 'work1-0g1b3grp436e9236'
})
const util= require('../../utils/util.js')
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Page({
    options: {
        styleIsolation: 'shared'
    },
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: {
            active: 'activeTabBarIndex'
        },
        actions: {
            updateActive: 'updateActiveTabBarIndex'
        },
    },

    /**
     * 页面的初始数据
     */
    data: {
      nickName: '',
      avatar: '',
      isLogin: false,
      gender: '',
      userOpenId: '',
      logoutActions: [
        { name: '退出', color: '#ee0a24' }
      ],
      showLogoutActionSheet: false,
      showNullCompany: false,
      nullCompanyActions: [
        { name: '前往', color: '#ee0a24' }
      ],
      // 测试账号
      showTestUsers: false,
      testUsersActions: [],
      testUsers: []
    },

    // 一键登录测试账户
    loginTest() {
        this.setData({showTestUsers: true})
    },

    onCloseTestUsersActionSheet() {
        this.setData({showTestUsers: false})
    },

    onSelectTestUsersActionSheet({detail}) {
        if (detail.name === '取消') {
            return
        }
        for (let i = 0; i < this.data.testUsers.length; i++) {
            const element = this.data.testUsers[i]
            if (element._id === detail._id) {
                wx.setStorageSync('userInfo', {
                    avatarUrl: element.avatar,
                    nickName: element.nickName,
                    userId: element._id,
                    userOpenId: element.openid
                })
                this.setData({avatar: element.avatar, nickName: element.nickName, isLogin: true})
                // 连接goEasy
                util.connectToGoEasy()
                break
            }
        }
        util.myToastSuccess('登录成功')
    },

    toCvFeedBack() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        wx.showLoading({
          title: '加载中...'
        })
        db.collection('work_post').where({userId: userInfo.userId}).get().then(res=>{
            wx.hideLoading()
            if (res.data.length === 0) {
                util.myToastNone('您还没有投递过简历哦～')
            } else {
                wx.navigateTo({url: '/pages/cvFeedback/cvFeedback'})
            }
        })
    },

    toCvInterview() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        wx.showLoading({
          title: '加载中...'
        })
        db.collection('work_company').where({userId: userInfo.userId}).get().then(res=>{
            wx.hideLoading()
            if (res.data.length === 0) {
                this.setData({showNullCompany: true})
            } else {
                wx.navigateTo({url: '/pages/cvInterview/cvInterview'})
            }
        })
    },

    toJobCollection() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        wx.navigateTo({url: '/pages/jobCollection/jobCollection'})
    },

    toUpJobPage() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        wx.showLoading({
          title: '加载中...'
        })
        db.collection('work_company').where({userId: userInfo.userId}).get().then(res=>{
            wx.hideLoading()
            if (res.data.length === 0) {
                this.setData({showNullCompany: true})
            } else {
                wx.navigateTo({url: '/pages/upJob/upJob'})
            }
        })
    },

    toFirmPage() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        // 检查是否为公司
        db.collection('work_company').where({userId: userInfo.userId}).get().then(res=>{
            if (res.data.length === 0) {
                this.setData({showNullCompany: true})
            } else {
                wx.navigateTo({url: '/pages/firm/firm?id=' + res.data[0]._id + '&toUpdate=1'})
            }
        })
    },

    toCvPreview() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        db.collection('work_cv').where({userId: userInfo.userId}).get().then(res=>{
            if (res.data.length === 0) {
                util.myToastError('请先制作简历～')
                return
            }
            // console.log(res.data[0]._id)
            wx.navigateTo({
                url: '/pages/cv-preview/cv-preview?_id=' + res.data[0]._id,
            })
        })
    },

    toCv() {
        // 检查是否登录
        if (!util.checkIfLogin()) {
            return
        }
        wx.navigateTo({
          url: '/pages/cv/cv',
        })
    },

    toRecordPage() {
        // 检查是否登录
        const userInfo = wx.getStorageSync('userInfo')
        if(!userInfo) {
            util.myToastError('请先登录～')
            return
        }
        wx.navigateTo({
          url: '/pages/record/record'
        })
    },

    toHelpPage() {
        wx.switchTab({
          url: '/pages/tutorial/tutorial'
        })
    },
  
    // 登录
    async login () {
        util.myLoading()
        let that = this
        await this.getOpenId()
        wx.getUserProfile({
          desc: '授权以开始使用',
          success: async res=>{
              res.userInfo['userOpenId'] = that.data.userOpenId
              const _id = await that.register(res.userInfo)
              res.userInfo['userId'] = _id
              wx.setStorageSync('userInfo', res.userInfo)
              // 连接goEasy
              util.connectToGoEasy()
              this.setData({
                  nickName: res.userInfo.nickName,
                  avatar: res.userInfo.avatarUrl,
                  isLogin: true
              })
          }, fail: res=>{
              util.myToastError('请授权后登录！')
          }
        })
    },

    register(userInfo) {
      return db.collection('work_user').where({
        openid: userInfo.userOpenId
      }).get().then(res=>{
        if (res.data.length === 0) {
          console.log('用户未注册~')
          db.collection('work_user').add({
            data: {
              avatar: userInfo.avatarUrl,
              nickName: userInfo.nickName,
              openid: userInfo.userOpenId
            }
          }).then(()=>{
            console.log('新增用户成功~')
          })
        } else {
          console.log('用户已注册~')
          return res.data[0]._id
        }
      }).catch(err=>{
        console.log('Register error', err);
      });
    },

    // 获取用户的唯一标识
    getOpenId() {
      let that = this
      wx.login({
        success(res){
          // console.log('code====',res.code);
          wx.request({
            url: 'https://api.itbear666.top/wxopenId/?jsCode=' + res.code,
            method:"GET",
            success(res){
              // console.log('openid=====',res);   // 得到openid
              that.setData({
                userOpenId: res.data.openid
              })
              // console.log('session_key====', res.data.session_key);   // 得到 session_key
            }
          })
        }
      })
    },

    // 退出登录选项相关
    openLogoutActionSheet() {
      this.setData({
        showLogoutActionSheet: true
      })
    },

    onSelectLogoutActionSheet(e) {
      if(e.detail.name === '退出') {
        this.setData({
          nickName: '未登录',
          avatar: '',
          isLogin: false,
          userOpenId: ''
        })
        wx.setStorageSync('userInfo', null)
        // 断开连接
        util.disconnectToGoEasy()
        util.myToastNone('退出成功')
      }
    },

    onCloseLogoutActionSheet() {
      this.setData({ showLogoutActionSheet: false })
    },

    // 我的公司相关
    onCloseNullCompanyActionSheet() {
        this.setData({ showNullCompany: false })
    },

    onSelectNullCompanyActionSheet(e) {
        if (e.detail.name === '前往') {
            util.myToastNone('前往注册')
            wx.navigateTo({url: '/pages/updateFirm/updateFirm'})
        }
    },

    // 随时获取当前用户信息
    getUserInfo() {
      const userInfo = wx.getStorageSync('userInfo')
      if(userInfo) {
          this.setData({
              nickName: userInfo.nickName,
              avatar: userInfo.avatarUrl,
              isLogin: true
          })
      } else {
          this.setData({avatar: 'https://776f-work1-0g1b3grp436e9236-1311803114.tcb.qcloud.la/avatar/keduck.jpg'})
      }
    },
  
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 加载测试账户
        db.collection('work_user').limit(10).where({nickName: db.RegExp({
            regexp: '农小农',
            options: 'i',
        })}).get().then(res=>{
            this.setData({testUsers: res.data})
            for (let i = 0; i < res.data.length; i++) {
                const ele = res.data[i]
                ele.name = ele.nickName
                ele.color = '#02c398'
            }
            this.setData({testUsersActions: res.data})
        })
    },
  
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
  
    },
  
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getUserInfo()
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
                this.updateActive(3)
        } 
    },
  
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
  
    },
  
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
  
    },
  
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
  
    },
  
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
  
    },
  
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
  
    }
  })